0. 路由
路由也就是地址,就是定义不同url访问不同页面的功能,可以实现导航、页面切换/跳转等功能。
1. 引入
1
| import { Router, Route, hashHistory } from 'react-router'
|
2. 配置
1 2 3 4
| <Router history={browserHistory}> <Route path="/" component={Home}></Route> <Route path="article" component={Article}></Route> </Router>
|
3. 通过Link实现跳转
1
| <Link to="/about">About</Link>
|
4.1 路由嵌套(公用导航)
1 2 3 4 5 6 7 8 9
| <Router history={hashHistory}> <Route path="/" component={App}> <Route path="/repos" component={Repos}/> <Route path="/about" component={About}/> </Route> </Router>
{this.props.children}
|
4.2 Active Links
1 2 3 4
| <Link to="/about" activeStyle={{ color: 'red' }}>About</Link> // 或者 活动类名 <li><Link to="/about" activeClassName="active">About</Link></li>
|
5. 传参
1 2 3 4 5 6 7
|
<Route path="/repos/:userName/:repoName" component={Repo}/>
<Link to="/repos/reactjs/react-router">React Router</Link> // 页面中访问参数 {this.props.params.repoName}
|
6. 嵌套路由下的默认页
1 2 3 4 5 6 7 8 9 10 11 12 13
| <Router history={hashHistory}> <Route path="/" component={App}>
{} <IndexRoute component={Home}/>
<Route path="/repos" component={Repos}> <Route path="/repos/:userName/:repoName" component={Repo}/> </Route> <Route path="/about" component={About}/> </Route> </Router>
|
7. 首页(默认页)路由地址
1 2 3 4 5 6
| <Link to="/"></Link>
<IndexLink to="/"></IndexLink>
<Link to="/" activeClassName="active" onlyActiveOnIndex={true}>Home</Link>
|
8. 更好的地址browserHistory
1 2 3 4 5 6 7
| import { browserHistory } from 'react-router'
<Router history={browserHistory}> {} </Router> // 其他方面没有变化
|
9. 路由跳转
1 2 3 4 5 6 7 8 9
| browserHistory.push(path)
contextType: { router: React.PropTypes.object }, this.context.router.push(path)
|
10. 路由钩子
每个路由都有Enter和Leave钩子,触发onEnter和onLeave。
ps:
阮一峰老师
github